﻿using System;

namespace UniversalApproach.Expands
{
    public static class DateTimeExpand
    {
        /// <summary>
        /// 使用自定义格式化字符串，转换时间
        /// </summary>
        /// <param name="s"></param>
        /// <param name="userFormat">自定义格式化字符串</param>
        /// <returns>如果自定义格式化字符串有错，返回内容为<see cref="DateTime.MinValue"/>。否则正常返回解析的时间</returns>
        public static DateTime ConvertToDateTimeByUserFormat(this string s, string userFormat)
        {
            var tmp = DateTime.MinValue;

            if (string.IsNullOrEmpty(userFormat)||string.IsNullOrWhiteSpace(userFormat))
            {
                return tmp;
            }

            if (!DateTime.TryParse(s, out tmp))
            {
                DateTime.TryParseExact(s, userFormat, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None,out tmp);
            }

            return tmp;
        }
    }
}